//===============================================================================
// Microsoft Architecture Strategy Team
// LitwareHR - SaaS Sample Application
//===============================================================================
// Copyright  Microsoft Corporation.  All rights reserved.
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE.
//===============================================================================
// The example companies, organizations, products, domain names,
// e-mail addresses, logos, people, places, and events depicted
// herein are fictitious.  No association with any real company,
// organization, product, domain name, email address, logo, person,
// places, or events is intended or should be inferred.
//===============================================================================


//===============================================================================
// Microsoft Architecture Strategy Team
// LitwareHR - S+S Sample Application
//===============================================================================
// Copyright  Microsoft Corporation.  All rights reserved.
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE.
//===============================================================================
// The example companies, organizations, products, domain names,
// e-mail addresses, logos, people, places, and events depicted
// herein are fictitious.  No association with any real company,
// organization, product, domain name, email address, logo, person,
// places, or events is intended or should be inferred.
//===============================================================================

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.OleDb;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;
using LitwareHR.PublicApp.WinUX.Search;
using System.Globalization;

namespace LitwareHR.PublicApp.WinUX.Search
{
    public sealed class WindowsDesktopSearch
    {
        private const string QUERY = "SELECT TOP 200 \"System.FileName\", \"System.ItemPathDisplay\" FROM SYSTEMINDEX..SCOPE() WHERE ";

        private WindowsDesktopSearch()
        {
        }

        public static DataTable ExecuteWindowsSearchQuery(string value)
        {
            DataTable wdsTable = null;

            if (value.Length == 0)
            {
                return wdsTable;
            }

            string connectionString = @"Provider=Search.CollatorDSO;Extended Properties='Application=Windows'";
            wdsTable = new DataTable("QueryResults");
            wdsTable.Locale = CultureInfo.InvariantCulture;

            try
            {
                using (OleDbConnection connection = new OleDbConnection(connectionString))
                {
                    connection.Open();

                    OleDbCommand cmd = new OleDbCommand( QUERY + " CONTAINS('" + value + "')", connection);

                    OleDbDataReader reader = cmd.ExecuteReader();
                    if (!reader.HasRows) { return (null); }

                    int numColumns = reader.FieldCount;

                    // Create a column in the datatable for each column returned in the query
                    for (int i = 0; i < numColumns; i++)
                        wdsTable.Columns.Add(reader.GetName(i));

                    object[] values = new object[numColumns];

                    while (reader.Read())
                    {
                        reader.GetValues(values);
                        string[] rowTextValues = GetRowTextValues(values);

                        wdsTable.Rows.Add(rowTextValues);
                    }
                }
            }//Exception will be thrown where WDS is not installed 
            catch (InvalidOperationException ex)
            {
               ExceptionPolicy.HandleException(ex, "Default Policy");
            }
            catch (OleDbException ex)
            {
                ExceptionPolicy.HandleException(ex, "Default Policy");
            }
            catch (Exception ex)
            {
                ExceptionPolicy.HandleException(ex, "Default Policy");
                throw;
            }

            return (wdsTable);
        }

        // Process a row from the query results, and combine any multi-valued columns
        static string[] GetRowTextValues(object[] QueryResultValues)
        {
            string[] textValues = new string[QueryResultValues.Length];
            for (int i = 0; i < QueryResultValues.Length; i++)
            {
                if (!QueryResultValues[i].GetType().IsArray)
                {
                    textValues[i] = QueryResultValues[i].ToString();
                }
                else
                {
                    int count = 0;
                    StringBuilder colValue = new StringBuilder();
                    foreach (object o in QueryResultValues[i] as Array)
                    {
                        if (count++ > 0)
                        {
                            colValue.Append(";");
                        }
                        colValue.Append(o.ToString());
                    }
                    textValues[i] = colValue.ToString();
                }
            }
            return (textValues);
        }

    }
}
